#pragma once
#include <pthread.h>

#include "Socket.hpp"

using namespace SocketModule;

using service_io_t = std::function<void(SockSPtr, Inet_Addr &)>;

class TcpServer
{
public:
    TcpServer(service_io_t service, uint16_t port)
        : _port(port), _isrunning(false), _listensockfd(std::make_shared<TcpSocket>()), _service(service)
    {
        _listensockfd->BuildListenSocket(_port);
    }

    class ThreadData
    {
    public:
        SockSPtr _sockfd;
        TcpServer *_self;
        Inet_Addr _addr;

    public:
        ThreadData(SockSPtr sockfd, TcpServer *self, const Inet_Addr &addr) : _sockfd(sockfd), _self(self), _addr(addr)
        {
        }
    };

    void Loop()
    {
        _isrunning = true;
        while (_isrunning)
        {
            Inet_Addr client;
            SockSPtr newsock = _listensockfd->Accepter(&client);
            if (newsock == nullptr)
                continue;
            LOG(FATAL, "get a new link, client info: %s sockfd is %d\n", client.AddrStr().c_str(), newsock->Sockfd());
            // 多线程
            pthread_t tid;
            ThreadData *td = new ThreadData(newsock, this, client);
            pthread_create(&tid, nullptr, Execute, td);
        }
        _isrunning = false;
    }

    static void *Execute(void *args)
    {
        ThreadData *td = static_cast<ThreadData *>(args);
        td->_self->_service(td->_sockfd, td->_addr);
        td->_sockfd->Close();
        delete td;
        return nullptr;
    }

    ~TcpServer() {}

private:
    uint16_t _port;
    SockSPtr _listensockfd;
    bool _isrunning;
    service_io_t _service;
};